﻿using System;

using System.Windows.Media;
using System.Windows.Xps.Packaging;
using System.Windows.Documents;
using System.Drawing;
using System.IO;
using System.Drawing.Imaging;
using System.Windows.Media.Imaging;

namespace Infrastructure
{
    public class XpsToJpgHelper
    {
        /// <summary>
        /// 开始转换
        /// </summary>
        /// <param name="xpsPath">xps的路径</param>
        /// <param name="saveImgPath">图片保存的路径</param>
        /// <returns></returns>
        public static void Generate(string xpsPath, string saveImgPath)
        {
            if (!File.Exists(xpsPath))
            {
                throw new Exception(string.Format("未找到Xps文件路径 '{0}'", xpsPath));
            }

            BitmapEncoder bitmapEncoder = null;
            MemoryStream memoryStream = new MemoryStream();
            XpsDocument xpsDocument;
            try
            {

                xpsDocument = new XpsDocument(xpsPath, System.IO.FileAccess.Read);
                FixedDocumentSequence documentPageSequence = xpsDocument.GetFixedDocumentSequence();

                bitmapEncoder = new JpegBitmapEncoder();
                for (int i = 0; i < documentPageSequence.DocumentPaginator.PageCount; i++)
                {
                    DocumentPage documentPage = documentPageSequence.DocumentPaginator.GetPage(i);
                    RenderTargetBitmap targetBitmap = new RenderTargetBitmap((int)documentPage.Size.Width, (int)documentPage.Size.Height, 96.0, 96.0, PixelFormats.Pbgra32);
                    targetBitmap.Render(documentPage.Visual);
                    bitmapEncoder.Frames.Add(BitmapFrame.Create(targetBitmap));
                }
                xpsDocument.Close();
                bitmapEncoder.Save(memoryStream);
                Bitmap bt = new System.Drawing.Bitmap(memoryStream);
                bt.Save(saveImgPath, ImageFormat.Jpeg);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                memoryStream.Close();
            }

        }

        public static void SaveXps(byte[] image, string fileName)
        {
            using (FileStream xps = File.Create(fileName))
            {
                xps.Write(image, 0, image.Length);
                xps.Flush();
            }
        }
    }
}
